package cn.car91.activity;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.CommentListAdapter;
import cn.car91.adapter.HardwareListAdapter;
import cn.car91.adapter.TechnologyListAdapter;
import cn.car91.bean.Service;
import cn.car91.bean.User;
import cn.car91.bean.WashShop;
import cn.car91.bean.WashShopComment;
import cn.car91.http.HttpHandler;
import cn.car91.pager.CommentPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.ImageManager;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.MyProgressDialog;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

public class WashShopDetailActivity extends BaseActivity {
    final static int Request_Code = 23001;
    boolean hadCollection = false;

    private CommentPager commentPager = new CommentPager();

    //详情页面参数
    String wid = null;
    String wname = null;
    List<ImageView> imageViews;
    @ViewInject(R.id.washshop_detail_pic)
    ViewPager viewPager;
    @ViewInject(R.id.washshop_detail_scroll)
    ScrollView washShopDetailScroll;
//    @ViewInject(R.id.repairshop_detail_comment_list)
//    ListView commentList;
//    @ViewInject(R.id.repairshop_detail_technology)
//    GridView techGridView;
//    @ViewInject(R.id.repairshop_detail_hardware)
//    GridView hardGridView;
//    @ViewInject(R.id.comment_score)
//    RadioGroup commentGroup;
//    @ViewInject(R.id.repairshop_detail_morecomment)
//    TextView moreComment;
//    @ViewInject(R.id.repairshop_detail_collection)
//    Button collectionBtn;
    @ViewInject(R.id.call_btn)
    Button callBtn;
    @ViewInject(R.id.comment_btn)
    Button commentBtn;

    WashShopDetailHandler washShopDetailHandler;
    CollectionBtnClickEvent collectionBtnClickEvent = new CollectionBtnClickEvent();

    CommentListAdapter<WashShopComment> commentListAdapter = null;
    TechnologyListAdapter technologyListAdapter = null;
    HardwareListAdapter hardwareListAdapter = null;

    //初始化一个自定义的Dialog
    Dialog dialog = null;

    String score = "0";
    String phoneNum;

    static ImageManager imageManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_washshop_detail);
        super.onCreate(savedInstanceState);
        imageManager = new ImageManager(WashShopDetailActivity.this, "sdcard/car91/temp/washshop");
        dialog = new MyProgressDialog(WashShopDetailActivity.this, R.style.MyProgressDialog);

        wid = getIntent().getStringExtra("wid");

        initView();
        if (RegexUtil.isNotNull(wid)) {
        	HttpHandler.httpHandler.getWashShopDetail(wid, callbackDetail);
        }

//        commentGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//			
//			@Override
//			public void onCheckedChanged(RadioGroup arg0, int arg1) {
//				switch (arg1) {
//				case R.id.comment_score_good:
//					score = "0";
//					break;
//				case R.id.comment_score_normal:
//					score = "1";
//					break;
//				case R.id.comment_score_bad:
//					score = "2";
//					break;
//
//				default:
//					break;
//				}
//                commentListAdapter.clear();
//                commentPager.reset();
//                commentPager.getRepairShopComment(rid,score, callbackRefreshCommentList);
//			}
//		});
    }

    /* 详情页面 */
    private class WashShopDetailHandler {
    	public ViewPager   washShopLogo;
//        public ImageView repairShopLogo;
        public TextView washShopName;
        public TextView washShopGood;
        public TextView washShopContent;
        public TextView washShopAddress;
        public TextView washShopContact;
        public Button washShopCollection;
        public TextView washShopDesc;
        public ImageView washShopLincence;
    }

    @SuppressLint("WrongViewCast")
	private void initView() {
    	washShopDetailHandler = new WashShopDetailHandler();
    	washShopDetailHandler.washShopLogo =  (ViewPager) findViewById(R.id.washshop_detail_pic);
    	washShopDetailHandler.washShopName = (TextView) findViewById(R.id.washshop_detail_name);
//        repairShopDetailHandler.repairShopGood = (TextView) findViewById(R.id.repairshop_detail_good);
//        repairShopDetailHandler.repairShopContent = (TextView) findViewById(R.id.repairshop_detail_content);
    	washShopDetailHandler.washShopAddress = (TextView) findViewById(R.id.washshop_detail_address);
    	washShopDetailHandler.washShopContact = (TextView) findViewById(R.id.washshop_detail_contact);
//        repairShopDetailHandler.repairShopCollection = (Button) findViewById(R.id.repairshop_detail_collection);
//        repairShopDetailHandler.repairShopDesc = (TextView) findViewById(R.id.repairshop_detail_desc);
//        repairShopDetailHandler.repairShopLincence = (ImageView) findViewById(R.id.repairshop_detail_lincence);
    }

    /**
     * 页面显示商家信息
     *
     * @param repairShop 商家
     */
    private void initData(WashShop washShop) {
        if (washShopDetailHandler != null && washShop != null) {
            imageManager.displayImage(getCar91Application().getCenterServerUrl() + "/" + washShop.getLogo(), washShopDetailHandler.washShopLogo, WashShopDetailActivity.this.getResources().getDrawable(R.drawable.ico_launcher));
            imageManager.displayImage(getCar91Application().getCenterServerUrl() + "/" + washShop.getDetail().getLicense(), washShopDetailHandler.washShopLincence, WashShopDetailActivity.this.getResources().getDrawable(R.drawable.ico_launcher));

            wname = washShop.getName();
            washShopDetailHandler.washShopName.setText(wname);

            try {
                Long count = washShop.getCommentcount();
                int good = 100;
                if (cn.car91.utils.RegexUtil.isNotNull(count)) {
                    good = (int) ((washShop.getGoodcount() * 1.0 / count) * 100);
                }
                washShopDetailHandler.washShopGood.setText("好评率：" + good + "%");
            } catch (Exception e) {
            }

            StringBuffer serviceStr = new StringBuffer();
            Set<Service> services = washShop.getDetail().getServices();
            if (services != null) {
                for (Service service : services) {
                    serviceStr.append(service.getName() + " ");
                }
            }

            washShopDetailHandler.washShopContent.setText(serviceStr);
            String addressHtml = "<font color='#0066cc'>&nbsp;<img src='" + R.drawable.map_point_red + "'/>查看地图</font>";
            washShopDetailHandler.washShopAddress.setText(washShop.getDetail().getAddress());
            washShopDetailHandler.washShopAddress.append(Html.fromHtml(addressHtml, imgGetter, null));

            phoneNum = washShop.getDetail().getPhone();
            if (RegexUtil.isNotNull(phoneNum)) {
                String[] numbers = phoneNum.split("\\s+");
                if (numbers.length > 0) {
                	washShopDetailHandler.washShopContact.setText(numbers[0]);
                }
            }

            washShopDetailHandler.washShopDesc.setText(Html.fromHtml(RegexUtil.htmlFilter(washShop.getDetail().getDesc())));

            //搜藏按钮事件
            collectionBtnClickEvent.setRid(washShop.getId());
            washShopDetailHandler.washShopCollection.setOnClickListener(collectionBtnClickEvent.onClickListener);

            //滚动置顶
            washShopDetailScroll.smoothScrollTo(0, 0);

            //地图
            MapClickEvent mapClickEvent;
            try {
                mapClickEvent = new MapClickEvent(washShop.getLon().doubleValue(), washShop.getLat().doubleValue(), washShop);
            } catch (Exception e) {
                String pointString = washShop.getDetail().getPosition();
                String[] points = pointString.split(",");
                mapClickEvent = new MapClickEvent(Double.valueOf(points[0]), Double.valueOf(points[1]), washShop);
            }
            washShopDetailHandler.washShopAddress.setOnClickListener(mapClickEvent.onClickListener);

            //留言栏
//            commentListAdapter = new CommentListAdapter(RepairShopDetailActivity.this, R.layout.view_comment_item);
//            commentList.setAdapter(commentListAdapter);
//            moreComment.setOnClickListener(onMoreCommentClickListener);

        //技术力量栏
//            technologyListAdapter = new TechnologyListAdapter(getApplicationContext());
//            techGridView.setAdapter(technologyListAdapter);
//            technologyListAdapter.setData(new ArrayList<Technology>(repairShop.getDetail().getTechnologies()));
//            technologyListAdapter.notifyDataSetChanged();

            //硬件设施栏
//            hardwareListAdapter = new HardwareListAdapter(getApplicationContext());
//            hardGridView.setAdapter(hardwareListAdapter);
//            hardwareListAdapter.setData(new ArrayList<Hardware>(repairShop.getDetail().getHardwares()));
//            hardwareListAdapter.notifyDataSetChanged();

            //底部
            callBtn.setOnClickListener(onCallClickListener);
            commentBtn.setOnClickListener(onCommentClickListener);

            ((TextView) findViewById(R.id.header_text)).setText(washShop.getName());

            commentPager.getWashShopComment(washShop.getId(),score, callbackRefreshCommentList);

            checkCollection();
        } else {
            new HerilyAlertDialog.Builder(WashShopDetailActivity.this)
                    .setMessage("该商家被关黑屋子\n或已被删除")
                    .create().show();
        }
    }

    /**
     * 收藏按钮事件
     * 文件 cn.car91.activity.RepairShopMainActivity.java
     *
     * @author 周海刚
     *         时间 2014年11月25日
     */
    private class CollectionBtnClickEvent {
        private String rid;

        public void setRid(String rid) {
            this.rid = rid;
        }

        public CollectionBtnClickEvent() {
            super();
        }

        public OnClickListener onClickListener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (RegexUtil.isNotNull(rid)) {
                    if (getCar91Application().getUser() == null) {
                        HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(WashShopDetailActivity.this);
                        //builder.setIcon(R.drawable.icon);
                        builder.setMessage("请先登录");
                        builder.setPositiveButton("登录", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //这里添加点击确定后的逻辑
                                Intent intent = new Intent();
                                intent.setClass(WashShopDetailActivity.this, UserLoginActivity.class);
                                startActivityForResult(intent, Request_Code);
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        });
                        builder.create().show();
                    } else {
                        if (hadCollection)
                        	HttpHandler.httpHandler.repairShopCollect(rid, getCar91Application().getUser().getId(), "d", callbackCollection);
                        else
                        	HttpHandler.httpHandler.repairShopCollect(rid, getCar91Application().getUser().getId(), "a", callbackCollection);
                    }
                }
            }
        };
    }

    OnClickListener onMoreCommentClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (RegexUtil.isNotNull(wid)) {
                commentPager.getRepairShopComment(wid,score, callbackRefreshCommentList);
            }
        }
    };

    private class MapClickEvent {
        private Double Lon;
        private Double Lat;
        private WashShop washShop;

        public MapClickEvent(Double Lon, Double Lat, WashShop washShop) {
            this.Lon = Lon;
            this.Lat = Lat;
            this.washShop = washShop;
        }

        public OnClickListener onClickListener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try {
                    if (Lat != null && Lon != null) {
                        Intent intent = new Intent();
                        intent.putExtra("lon", Lon);
                        intent.putExtra("lat", Lat);
                        intent.putExtra("name", washShopDetailHandler.washShopName.getText().toString());
                        intent.putExtra("washshop", (Serializable) washShop);
                        intent.setClass(WashShopDetailActivity.this, MapActivity.class);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        };
    }

    /**
     * html获取本地图片资源
     */
    ImageGetter imgGetter = new ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            // TODO Auto-generated method stub  
            int id = Integer.parseInt(source);
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    /**
     * 回调获取商家详情
     */
    private RequestCallBack callbackDetail = new RequestCallBack() {

        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            if (dialog != null)
                if (!dialog.isShowing())
                    dialog.show();
        }

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "网络不给力啊~", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            if (dialog != null)
                if (dialog.isShowing())
                    dialog.cancel();
            initData((WashShop) Car91JsonUtil.getDTO(arg0.result.toString(), WashShop.class));
        }
    };

	/* 留言 */
    /**
     * 回调获取商家有关留言
     */
//    private RequestCallBack callbackCommentList = new RequestCallBack() {
//
//        @Override
//        public void onStart() {
//            // TODO Auto-generated method stub
//            super.onStart();
//            moreComment.setText(R.string.repairshop_more_comment_loading);
//        }

//        @Override
//        public void onFailure(HttpException arg0, String arg1) {
//            // TODO Auto-generated method stub
//            moreComment.setText(R.string.repairshop_more_comment);
//        }

//        @Override
//        public void onSuccess(ResponseInfo arg0) {
//            // TODO Auto-generated method stub
//            try {
//                List<RepairShopComment> comments = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShopComment.class);
//                if(comments.size()>0){
//	                commentListAdapter.addData(comments);
//	                commentListAdapter.notifyDataSetChanged();
//	                moreComment.setText(getString(R.string.repairshop_more_comment));
//                }else{
//                	moreComment.setText("没有更多评论啦");
//                }
//            } catch (Exception e) {
//
//            }
//            moreComment.setText(R.string.repairshop_more_comment);
//        }
//    };

    private RequestCallBack callbackRefreshCommentList = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            try {
                List<WashShopComment> comments = Car91JsonUtil.getDTOList(arg0.result.toString(), WashShopComment.class);
                commentListAdapter.setData(comments);
                commentListAdapter.notifyDataSetChanged();
            } catch (Exception e) {
            }
        }
    };

    private RequestCallBack callbackCollection = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            Integer state = Integer.valueOf(arg0.result.toString());

//            if (state != null) {
//                Drawable drawable = null;
//                switch (state) {
//                    case 1:
//                        hadCollection = true;
//                        Toast.makeText(getApplicationContext(), "收藏成功", Toast.LENGTH_SHORT).show();
//                        drawable = getResources().getDrawable(R.drawable.collection_had);
//                        break;
//                    case 11:
//                        hadCollection = false;
//                        Toast.makeText(getApplicationContext(), "已取消收藏", Toast.LENGTH_SHORT).show();
//                        drawable = getResources().getDrawable(R.drawable.collection_none);
//                        break;
//                    default:
//                        Toast.makeText(getApplicationContext(), "收藏失败", Toast.LENGTH_SHORT).show();
//                        break;
//                }
//                if (drawable != null) {
//                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                    collectionBtn.setCompoundDrawables(null, drawable, null, null);
//                }
//            }
        }
    };

    private void checkCollection() {
        User user = getCar91Application().getUser();
        if (user != null && RegexUtil.isNotNull(wid)) {
        	HttpHandler.httpHandler.checkWashShopCollect(wid, user.getId(), callbackCheckCollection);
        }
    }

    private RequestCallBack callbackCheckCollection = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            Integer state = Integer.valueOf(arg0.result.toString());
            if (state != null) {
                Drawable drawable = null;
                switch (state) {
                    case 1:
                        hadCollection = true;
                        drawable = getResources().getDrawable(R.drawable.collection_had);
                        break;
                    default:
                        hadCollection = false;
                        drawable = getResources().getDrawable(R.drawable.collection_none);
                        break;
                }
                if (drawable != null) {
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                    collectionBtn.setCompoundDrawables(null, drawable, null, null);
                }
            }
        }
    };

    //拨号
    private OnClickListener onCallClickListener = new OnClickListener() {
        Pattern phonePattern = Pattern.compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}");
        List<String> allNumber;
        Intent intent;

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (washShopDetailHandler != null) {
                intent = new Intent();
                if (RegexUtil.isNotNull(phoneNum)) {
                	try {
                		String[] numbers = phoneNum.split("\\s+");
                        intent.setAction(Intent.ACTION_CALL);
                        if (numbers.length == 1) {
                            Matcher matcher = phonePattern.matcher(numbers[0]);
                            if (matcher.find()) {
                                intent.setData(Uri.parse("tel:" + matcher.group()));
                            } else {
                                intent.setAction(Intent.ACTION_DIAL);
                            }
                            startActivity(intent);
                        } else if (numbers.length > 1) {
                            allNumber = Arrays.asList(numbers);
                            new HerilyAlertDialog.Builder(WashShopDetailActivity.this)
                                    .setTitle("服务热线")
                                    .setItems(numbers, new DialogInterface.OnClickListener() {
    									
    									@Override
    									public void onClick(DialogInterface arg0, int arg1) {
    										try {
    						                    Matcher matcher = phonePattern.matcher(allNumber.get(arg1));
    						                    if (matcher.find()) {
    						                        intent.setData(Uri.parse("tel:" + matcher.group()));
    						                    } else {
    						                        intent.setAction(Intent.ACTION_DIAL);
    						                    }
    						                } catch (Exception e) {
    						                    intent.setAction(Intent.ACTION_DIAL);
    						                }
    						                startActivity(intent);
    									}
    								})
                                    .setNegativeButton("取消", null)
                                    .create()
                                    .show();
                        }
					} catch (Exception e) {
						intent.setAction(Intent.ACTION_DIAL);
	                    startActivity(intent);
					}
                } else {
                    intent.setAction(Intent.ACTION_DIAL);
                    startActivity(intent);
                }
            }
        }
    };

    //留言评论
    private OnClickListener onCommentClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (RegexUtil.isNotNull(wid)) {
                if (getCar91Application().getUser() != null) {
                    Intent intent = new Intent();
                    intent.setClass(WashShopDetailActivity.this, WashShopCommentActivity.class);
                    intent.putExtra("wname", wname);
                    intent.putExtra("wid", wid);
                    startActivityForResult(intent, Request_Code);
                } else {
                    HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(WashShopDetailActivity.this);
                    //builder.setIcon(R.drawable.icon);
                    builder.setMessage("请先登录");
                    builder.setPositiveButton("登录", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //这里添加点击确定后的逻辑
                            Intent intent = new Intent();
                            intent.setClass(WashShopDetailActivity.this, UserLoginActivity.class);
                            startActivityForResult(intent, Car91ResultCode.Refresh_User_Code);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        }
                    });
                    builder.create().show();
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        //Toast.makeText(RepairShopDetailActivity.this, "request:"+requestCode+" result:"+resultCode+" init:"+Request_Code, Toast.LENGTH_LONG).show();
        if (requestCode == Request_Code) {
            switch (resultCode) {
                case RESULT_OK:
                    commentListAdapter.clear();
                    commentPager.reset();
                    commentPager.getWashShopComment(wid,score, callbackRefreshCommentList);
                case Car91ResultCode.Refresh_User_Code:
                    checkCollection();
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
